get.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { UserService } from '@/server/modules/users/user.service';
  3. import { z } from 'zod';
  4. import { authMiddleware } from '@/server/middleware/auth.middleware';
  5. import { ErrorSchema } from '@/server/utils/errorHandler';
  6. import { AppDataSource } from '@/server/data-source';
  7. import { AuthContext } from '@/server/types/context';
  8. import { UserSchema } from '@/server/modules/users/user.entity';
  9. const userService = new UserService(AppDataSource);
  10. const GetParams = z.object({
  11. id: z.string().openapi({
  12. param: { name: 'id', in: 'path' },
  13. example: '1',
  14. description: '用户ID'
  15. })
  16. });
  17. const routeDef = createRoute({
  18. method: 'get',
  19. path: '/{id}',
  20. middleware: [authMiddleware],
  21. request: {
  22. params: GetParams
  23. },
  24. responses: {
  25. 200: {
  26. description: '成功获取用户详情',
  27. content: { 'application/json': { schema: UserSchema } }
  28. },
  29. 404: {
  30. description: '用户不存在',
  31. content: { 'application/json': { schema: ErrorSchema } }
  32. },
  33. 500: {
  34. description: '服务器错误',
  35. content: { 'application/json': { schema: ErrorSchema } }
  36. }
  37. }
  38. });
  39. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  40. try {
  41. const { id } = c.req.valid('param');
  42. const user = await userService.getUserById(parseInt(id));
  43. if (!user) {
  44. return c.json({ code: 404, message: '用户不存在' }, 404);
  45. }
  46. return c.json(user, 200);
  47. } catch (error) {
  48. return c.json({
  49. code: 500,
  50. message: error instanceof Error ? error.message : '获取用户详情失败'
  51. }, 500);
  52. }
  53. });
  54. export default app;